<script lang="ts" setup>
import { reactive, ref, defineProps, onMounted, onBeforeMount } from "vue";
import { ElMessage, ElButton, FormInstance, FormRules } from "element-plus";
import { Delete, Plus } from "@element-plus/icons-vue";
import { UploadProps, UploadFile, TabsPaneContext } from "element-plus";
import { addProductApi, productInfoApi, updateProductInfoApi, classify1ListNameApi, unitListNameApi } from "@/apis/productApi";
import { Product } from '@/pojo/dto/Product'
import { number } from "echarts";
import rc4 from "crypto-js/rc4";
import { res } from '@/pojo/dto/res'
import SButton from "@/views/content/util/button/sButton.vue"

//控制参数
const props = defineProps({
  //编辑
  isupdate: {
    type: Number,
    default: () => 0,
  },
  pid: {
    type: Number,
    default: () => null,
  },
})
const isupdate = ref(0); //默认不做数据回显
const pid = ref(null); //回显商品id
const echoProduct = ref<Product>(); //接收回显数据

const ruleFormRef = ref<FormInstance>();

const classify1ListName = ref([])
const unitListName = ref([])
//绑定数据表单
const ruleForm = reactive<Product>({
  //基础
  productId: null,
  sort: "",
  name: "",
  classify: "",
  unit: "",
  imgList: [],
  imgs: [],
  morenPrice: null,
  morenpckMoney: 0,
  morenNumber: 999,
  delivery: true,
  oneselfBuy: true,
  feature: [],
  participate: true,
  desc: "",
  //扩展
  specificationList: [],
  propertyList: [],
  chargeList: [],
  sellDateType: "全日期售卖",
  sellTimeType: "24H全天",
  allDateSell: true,
  allTimeSell: true,
  sellDateScope: [],
  sellWeekDay: [],
  sellTimeScope: [],
  min_number: 1,
});
//校验更新内容表单
const verifyRuleForm = reactive<Product>({
  //基础
  productId: null,
  sort: "",
  name: "",
  classify: "",
  unit: "",
  imgList: [],
  imgs: [],
  morenPrice: null,
  morenpckMoney: 0,
  morenNumber: 999,
  delivery: true,
  oneselfBuy: true,
  feature: [],
  participate: true,
  desc: "",
  //扩展
  specificationList: [],
  propertyList: [],
  chargeList: [],
  sellDateType: "全日期售卖",
  sellTimeType: "24H全天",
  allDateSell: true,
  allTimeSell: true,
  sellDateScope: [],
  sellWeekDay: [],
  sellTimeScope: [],
  min_number: 1,
});
//更新提交表单
const updateSubmitForm = reactive<Product>({
  //基础
  productId: null,
  sort: "",
  name: "",
  classify: "",
  unit: "",
  imgList: [null, null, null, null],
  imgs: [null, null, null, null],
  morenPrice: null,
  morenpckMoney: null,
  morenNumber: null,
  delivery: null,
  oneselfBuy: null,
  feature: [],
  participate: null,
  desc: "",
  //扩展
  specificationList: [null],
  propertyList: [null],
  chargeList: [null],
  sellDateType: "",
  sellTimeType: "",
  allDateSell: null,
  allTimeSell: null,
  sellDateScope: [],
  sellWeekDay: [],
  sellTimeScope: [],
  min_number: null,
});

//表单需要校验项(必填)
const rules = reactive<FormRules<Product>>({
  name: [
    { required: true, message: "请输入商品名称", trigger: "blur" },
    { min: 1, max: 30, message: "商品名称长度不得超过30", trigger: "blur" },
  ],
  classify: [
    {
      required: true,
      message: "请选择商品分类",
      trigger: "change",
    },
  ],
  unit: [
    {
      required: true,
      message: "请选择商品单位",
      trigger: "change",
    },
  ],
  imgList: [
    {
      required: true,
      message: "请选择商品主图",
      trigger: "change",
    },
  ],
  morenPrice: [
    {
      required: true,
      message: "请输入价格",
      trigger: "change",
    },
  ],
});

//关闭
const emit = defineEmits(["exitAddProductPage"]);
function goBack() {
  emit("exitAddProductPage", "productList");
}
//-------------------------------------------------------------------tab标签---------------------------------------------------------
const activeName = ref("first");

const handleClick = (tab: TabsPaneContext, event: Event) => {
  // console.log(tab, event);
};
//-------------------------------------------------------------------文件上传-----------------------------------------------------------
const dialogImageUrl = ref(""); //预览图片路径
const dialogVisible = ref(false); //预览框可见
const disabled = ref(false); //功能禁用
const validImageFormats = ["jpg", "jpeg", "png"];
//删除
const handleRemove: UploadProps["onRemove"] = (file: UploadFile) => {
  // console.log("删除图片：");
  // console.log(ruleForm.imgList);
};
//预览
const handlePictureCardPreview: UploadProps["onPreview"] = (
  file: UploadFile
) => {
  dialogImageUrl.value = file.url!;
  dialogVisible.value = true;
};
//选择文件格式校验//并限制上传数量
const checkImageFormat = (file) => {
  // console.log("文件格式校验");
  // console.log(file);
  const fileFormat = file.name.split(".").pop().toLowerCase(); // 获取文件格式
  if (!validImageFormats.includes(fileFormat)) {
    ElMessage({ type: "error", message: "商品图片格式必须为 jpg/jpeg/png" });
    ruleForm.imgList.pop(); //删除格式不符合的文件
    return false; // 阻止文件上传
  }
  if (ruleForm.imgList.length > 3) {
    ElMessage({ type: "error", message: "商品图片达到上限" });
    ruleForm.imgList.pop(); //删除格式不符合的文件
    return false;
  }
  return true; // 允许文件上传
};
//---------------------------------------------------------------------表单常规信息------------------------------------------------------------------
//---------------------------------------------------------------------扩展信息----------------------------------------------------------------

//添加规格
const addSpecification = () => {
  if (ruleForm.specificationList.length >= 20) {
    ElMessage({ type: "error", message: "规格数量达到上限！" });
    return;
  }
  ruleForm.specificationList.push({
    id: null,
    name: "",
    price: 0,
    pckMoney: 0,
    number: 99,
  });
};
//删除规格
const delSpec = (index: number) => {
  ruleForm.specificationList.splice(index, 1);
};
//添加属性
const addProperty = () => {
  if (ruleForm.propertyList.length >= 20) {
    ElMessage({ type: "error", message: "属性数量达到上限！" });
    return;
  }
  ruleForm.propertyList.push({
    id: null,
    name: "",
    value: [
      //最多10个值
      '',
      '',
      '',
      '',
      '',
      '',
      '',
      '',
      '',
      '',
    ],
  });
};
//删除属性
const delProp = (index: number) => {
  ruleForm.propertyList.splice(index, 1);
};

//添加加料
const addCharge = () => {
  if (ruleForm.chargeList.length >= 20) {
    ElMessage({ type: "error", message: "加料数量达到上限！" });
    return;
  }
  ruleForm.chargeList.push({
    id: null,
    name: "",
    price: 0,
  });
};
//删除加料
const delCharge = (index: number) => {
  ruleForm.chargeList.splice(index, 1);
};

//时间格式处理(转为数据路存储格式)
const dateToString = () => {
  ruleForm.sellDateScope[0] = new Date(ruleForm.sellDateScope[0]).toLocaleString().slice(0, 10);
  ruleForm.sellDateScope[1] = new Date(ruleForm.sellDateScope[1]).toLocaleString().slice(0, 10);
};
const showDateSelect = ref(false);
const showTimeSelect = ref(false);

//全日期售卖
const allDate = () => {
  ruleForm.allDateSell = true;
  // ruleForm.sellDateScope = [];
  // ruleForm.sellTimeScope = [];
  // ruleForm.sellWeekDay = [];
  showDateSelect.value = false;
};
//自定义日期售卖
const customDate = () => {
  ruleForm.allDateSell = false;
  showDateSelect.value = true;
};
//24H全天
const allTime = () => {
  ruleForm.allTimeSell = true;
  // ruleForm.sellTimeScope = [];
  showTimeSelect.value = false;
};
//自定义每天时间段售卖
const customTime = () => {
  ruleForm.allTimeSell = false;
  showTimeSelect.value = true;
};

const pickerFormatText = ref("HH:mm");
const minPickerTime = ref("08:00:00");

const changeTime = (evevt) => {
  minPickerTime.value = `${event}:00`;
};

const formSize = ref("default");

//价格格式转换为保留小数点两位
const handlePrice = () => {
  if (ruleForm.morenPrice != null) {
  }
};

//添加商品图片预处理转base64
const imgFileToBase64 = async (handleForm: Product) => {
  //图片文件处理
  if (handleForm.imgList.length > 0) {
    //置空操作
    handleForm.imgs = []
    const promises = [];
    for (let i = 0; i < handleForm.imgList.length; i++) {
      if (handleForm.imgList[i] != null) {
        const reader = new FileReader()

        const promise = new Promise((resolve, reject) => {
          reader.onload = () => {
            const base64String = reader.result
            // console.log(base64String)
            resolve(base64String)
          }

          reader.onerror = () => {
            reject(new Error("读取文件失败"));
          }
        })
        console.log(handleForm.imgList[i])
        reader.readAsDataURL(handleForm.imgList[i].raw)
        promises.push(promise)
      }
      if (handleForm.imgList[i] == null) {
        const promise = new Promise((resolve, reject) => {
          resolve(null)

        })
        promises.push(promise)
      }

    }
    await Promise.all(promises)
      .then((base64Strings) => {
        ruleForm.imgs.push(...base64Strings) // 使用扩展操作符将多个元素添加到数组中
      })
      .catch((error) => {
        console.error(error)
      });
  }
  return true
}
//提交表单(添加商品)
const submitForm = async (formEl: FormInstance | undefined) => {
  console.log(ruleForm);
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      //图片文件处理
      const rest = await imgFileToBase64(ruleForm)
      //拓展部分属性，加料，规格处理
      if (ruleForm.specificationList.length > 0) {
        for (let i = ruleForm.specificationList.length - 1; i >= 0; i--) {
          // 过滤掉未填写数据
          if (ruleForm.specificationList[i].name === '') {
            ruleForm.specificationList.splice(i, 1);
            console.log('规格过滤成功');
          }
        }
      }

      if (ruleForm.chargeList.length > 0) {
        for (let i = ruleForm.chargeList.length - 1; i >= 0; i--) {
          // 过滤掉未填写信息
          if (ruleForm.chargeList[i].name == '') {
            ruleForm.chargeList.splice(i, 1);
            console.log('加料过滤成功');
          }
        }
      }

      if (ruleForm.propertyList.length > 0) {
        for (let i = ruleForm.propertyList.length - 1; i >= 0; i--) {
          // 过滤掉未填写信息
          if (ruleForm.propertyList[i].name == '') {
            ruleForm.propertyList.splice(i, 1);
            console.log('属性过滤成功');
            continue;
          }
          if (ruleForm.propertyList[i].name != '') {
            let count = 0;
            for (let j = 0; j < ruleForm.propertyList[i].value.length; j++) {
              if (ruleForm.propertyList[i].value[j] != '') {
                count++;
              }
            }
            count > 0 ? null : ElMessage({ type: 'error', message: '请至少填写一项属性值' });
          }
        }
      }

      const res: res = await addProductApi(ruleForm);
      if (res.code === 0) {
        ElMessage({ type: "success", message: "保存成功！" });
        goBack();
      } else {
        ElMessage({ type: "error", message: "保存失败！" });
      }

    }

    else {
      ElMessage({ type: "error", message: "请正确填写商品必要信息！" });
    }
  }
  );
};
//提交表单(编辑商品)---------------------------------------------------------------------------------------------------------------------------------------
const submitUpdateForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      //校验用户的修改项
      //基础
      updateSubmitForm.productId = ruleForm.productId//ok

      ruleForm.sort != verifyRuleForm.sort ? updateSubmitForm.sort = ruleForm.sort : null//ok

      ruleForm.name != verifyRuleForm.name ? updateSubmitForm.name = ruleForm.name : null//ok

      ruleForm.classify != verifyRuleForm.classify ? updateSubmitForm.classify = ruleForm.classify : null//ok

      ruleForm.unit != verifyRuleForm.unit ? updateSubmitForm.unit = ruleForm.unit : null//ok

      ruleForm.desc != verifyRuleForm.desc ? updateSubmitForm.desc = ruleForm.desc : null//OK

      ruleForm.morenPrice != verifyRuleForm.morenPrice ? updateSubmitForm.morenPrice = ruleForm.morenPrice : null//OK

      ruleForm.morenpckMoney != verifyRuleForm.morenpckMoney ? updateSubmitForm.morenpckMoney = ruleForm.morenpckMoney : null//OK

      ruleForm.morenNumber != verifyRuleForm.morenNumber ? updateSubmitForm.morenNumber = ruleForm.morenNumber : null//OK



      //获取图片下标集合
      var img_indexs = []
      var updateImg_indexs = []
      for (let i = 0; i < verifyRuleForm.imgList.length; i++) {
        updateImg_indexs.push(verifyRuleForm.imgList[i].name)
        img_indexs.push(verifyRuleForm.imgList[i].name)
      }
      //找出被修改的图片下标
      for (let i = 0; i < updateImg_indexs.length; i++) {
        for (let j = 0; j < ruleForm.imgList.length; j++) {
          //未被修改
          if (updateImg_indexs[i] == ruleForm.imgList[j].name) {
            updateImg_indexs.splice(i, 1)
          }
        }
      }
      console.log('被替换的下标集合：')
      console.log(updateImg_indexs)

      //根据被替换的下标封装新图片数据
      for (let j = 0; j < ruleForm.imgList.length; j++) {
        //找出被替换的图片
        if (!img_indexs.includes(ruleForm.imgList[j].name)) {
          //处理新增
          if (updateImg_indexs.length == 0 && verifyRuleForm.imgList.length < ruleForm.imgList.length) {
            updateSubmitForm.imgList[j] = ruleForm.imgList[j]
          }
          //处理被修改图片
          if (updateImg_indexs.length > 0) {
            updateSubmitForm.imgList[updateImg_indexs[0]] = ruleForm.imgList[j]
            updateImg_indexs.splice(0, 1)
          }
        }
      }
      let deleted_indexs = []
      //最后确定被删除的图片
      console.log(updateImg_indexs)
      for (let i = 0; i < updateImg_indexs.length; i++) {
        for (let j = 0; j < verifyRuleForm.imgList.length; j++) {
          if (j == updateImg_indexs[i]) {
            deleted_indexs.push(j)
            console.log('标记删除')
            console.log(j)
          }
        }
      }

      await imgFileToBase64(updateSubmitForm)
      JSON.stringify(ruleForm.imgs) != JSON.stringify(verifyRuleForm.imgs) ? updateSubmitForm.imgs = ruleForm.imgs : null

      for (let i = 0; i < deleted_indexs.length; i++) {
        updateSubmitForm.imgs[deleted_indexs[i]] = 'delete'
      }


      ruleForm.delivery != verifyRuleForm.delivery ? updateSubmitForm.delivery = ruleForm.delivery : null//OK--

      ruleForm.oneselfBuy != verifyRuleForm.oneselfBuy ? updateSubmitForm.oneselfBuy = ruleForm.oneselfBuy : null//OK--


      ruleForm.participate != verifyRuleForm.participate ? updateSubmitForm.participate = ruleForm.participate : null//ok--

      ruleForm.feature != verifyRuleForm.feature ? updateSubmitForm.feature = ruleForm.feature : null//ok

      //拓展部分
      //校验规格是否被修改
      if ((JSON.stringify(ruleForm.specificationList) != JSON.stringify(verifyRuleForm.specificationList))) {//ok
        updateSubmitForm.specificationList = []
        var spec_ids = []//规格id集合
        for (let i = 0; i < verifyRuleForm.specificationList.length; i++) {
          spec_ids.push(verifyRuleForm.specificationList[i].id)
        }
        console.log('规格id集合：')
        console.log(spec_ids)
        //处理规格修改
        //找出被删除id集合
        for (let i = 0; i < spec_ids.length; i++) {
          for (let j = 0; j < ruleForm.specificationList.length; j++) {
            //排除未删除id
            if (spec_ids[i] == ruleForm.specificationList[j].id) {
              spec_ids.splice(i, 1)
            }
          }
        }
        //判断用户对每个项的操作：直接修改---删除+新增+修改原有（最终需要新增：删除的id【全部】分配给新增的）---删除+新增+修改原有（最终需要删除：删除的id【部分】分配给新增的，剩余id进行物理删除）
        for (let i = 0; i < ruleForm.specificationList.length; i++) {
          //被修改
          if (ruleForm.specificationList[i].id != null) {
            for (let j = 0; j < verifyRuleForm.specificationList.length; j++) {
              if (ruleForm.specificationList[i].id == verifyRuleForm.specificationList[j].id) {
                if (JSON.stringify(ruleForm.specificationList[i]) != JSON.stringify(verifyRuleForm.specificationList[j])) {
                  updateSubmitForm.specificationList.push(ruleForm.specificationList[i])
                }
              }
            }
          }
          //删除掉一个又添加一个
          if (ruleForm.specificationList[i].id == null) {
            console.log('需要分配id:')
            console.log(ruleForm.specificationList[i])

            //检查是否有被删除id分配
            if (spec_ids.length > 0) {
              for (let j = 0; j < spec_ids.length; j++) {
                ruleForm.specificationList[i].id = spec_ids[j]
                spec_ids.splice(j, 1)//分配id后将删除项id移除
                console.log('分配id：')
                console.log(ruleForm.specificationList[i])
                //移除后将新分配id的项视为修改
                updateSubmitForm.specificationList.push(ruleForm.specificationList[i])
                break
              }
            }
            //id被分配完，处理新增
            if (spec_ids.length == 0 && ruleForm.specificationList[i].id == null) {
              ruleForm.specificationList[i].name = ruleForm.specificationList[i].name + '_add'
              updateSubmitForm.specificationList.push(ruleForm.specificationList[i])
            }
          }
        }
        //最终确定需要删除的项
        for (let i = 0; i < spec_ids.length; i++) {
          for (let j = 0; j < verifyRuleForm.specificationList.length; j++) {
            if (verifyRuleForm.specificationList[j].id == spec_ids[i]) {
              verifyRuleForm.specificationList[j].name = verifyRuleForm.specificationList[j].name + '_delete'
              updateSubmitForm.specificationList.push(verifyRuleForm.specificationList[j])
            }
          }
        }
      }

      //校验属性是否被修改
      if ((JSON.stringify(ruleForm.propertyList) != JSON.stringify(verifyRuleForm.propertyList))) {//ok
        updateSubmitForm.propertyList = []
        var prop_ids = []//属性id集合
        for (let i = 0; i < verifyRuleForm.propertyList.length; i++) {
          prop_ids.push(verifyRuleForm.propertyList[i].id)
        }
        console.log('属性id集合：')
        console.log(prop_ids)
        //处理属性修改
        //找出被删除id集合
        for (let i = 0; i < prop_ids.length; i++) {
          for (let j = 0; j < ruleForm.propertyList.length; j++) {
            //排除未删除id
            if (prop_ids[i] == ruleForm.propertyList[j].id) {
              prop_ids.splice(i, 1)
            }
          }
        }
        //判断用户对每个项的操作：直接修改---删除+新增+修改原有（最终需要新增：删除的id【全部】分配给新增的）---删除+新增+修改原有（最终需要删除：删除的id【部分】分配给新增的，剩余id进行物理删除）
        for (let i = 0; i < ruleForm.propertyList.length; i++) {
          //被修改
          if (ruleForm.propertyList[i].id != null) {
            for (let j = 0; j < verifyRuleForm.propertyList.length; j++) {
              if (ruleForm.propertyList[i].id == verifyRuleForm.propertyList[j].id) {
                if (JSON.stringify(ruleForm.propertyList[i]) != JSON.stringify(verifyRuleForm.propertyList[j])) {
                  updateSubmitForm.propertyList.push(ruleForm.propertyList[i])
                }
              }
            }
          }
          //删除掉一个又添加一个
          if (ruleForm.propertyList[i].id == null) {
            console.log('需要分配id:')
            console.log(ruleForm.propertyList[i])

            //检查是否有被删除id分配
            if (prop_ids.length > 0) {
              for (let j = 0; j < prop_ids.length; j++) {
                ruleForm.propertyList[i].id = prop_ids[j]
                prop_ids.splice(j, 1)//分配id后将删除项id移除
                console.log('分配id：')
                console.log(ruleForm.propertyList[i])
                //移除后将新分配id的项视为修改
                updateSubmitForm.propertyList.push(ruleForm.propertyList[i])
                break
              }
            }
            //id被分配完，处理新增
            if (prop_ids.length == 0 && ruleForm.propertyList[i].id == null) {
              ruleForm.propertyList[i].name = ruleForm.propertyList[i].name + '_add'
              updateSubmitForm.propertyList.push(ruleForm.propertyList[i])
            }
          }
        }
        //最终确定需要删除的项
        for (let i = 0; i < prop_ids.length; i++) {
          for (let j = 0; j < verifyRuleForm.propertyList.length; j++) {
            if (verifyRuleForm.propertyList[j].id == prop_ids[i]) {
              verifyRuleForm.propertyList[j].name = verifyRuleForm.propertyList[j].name + '_delete'
              updateSubmitForm.propertyList.push(verifyRuleForm.propertyList[j])
            }
          }
        }
      }

      //校验加料是否被修改
      if ((JSON.stringify(ruleForm.chargeList) != JSON.stringify(verifyRuleForm.chargeList))) {//ok
        updateSubmitForm.chargeList = []
        var charge_ids = []//属性id集合
        for (let i = 0; i < verifyRuleForm.chargeList.length; i++) {
          charge_ids.push(verifyRuleForm.chargeList[i].id)
        }
        console.log('加料id集合：')
        console.log(charge_ids)
        //处理属性修改
        //找出被删除id集合
        for (let i = 0; i < charge_ids.length; i++) {
          for (let j = 0; j < ruleForm.chargeList.length; j++) {
            //排除未删除id
            if (charge_ids[i] == ruleForm.chargeList[j].id) {
              charge_ids.splice(i, 1)
            }
          }
        }
        //判断用户对每个项的操作：直接修改---删除+新增+修改原有（最终需要新增：删除的id【全部】分配给新增的）---删除+新增+修改原有（最终需要删除：删除的id【部分】分配给新增的，剩余id进行物理删除）
        for (let i = 0; i < ruleForm.chargeList.length; i++) {
          //被修改
          if (ruleForm.chargeList[i].id != null) {
            for (let j = 0; j < verifyRuleForm.chargeList.length; j++) {
              if (ruleForm.chargeList[i].id == verifyRuleForm.chargeList[j].id) {
                if (JSON.stringify(ruleForm.chargeList[i]) != JSON.stringify(verifyRuleForm.chargeList[j])) {
                  updateSubmitForm.chargeList.push(ruleForm.chargeList[i])
                }
              }
            }
          }
          //删除掉一个又添加一个
          if (ruleForm.chargeList[i].id == null) {
            console.log('需要分配id:')
            console.log(ruleForm.chargeList[i])

            //检查是否有被删除id分配
            if (charge_ids.length > 0) {
              for (let j = 0; j < charge_ids.length; j++) {
                ruleForm.chargeList[i].id = charge_ids[j]
                charge_ids.splice(j, 1)//分配id后将删除项id移除
                console.log('分配id：')
                console.log(ruleForm.chargeList[i])
                //移除后将新分配id的项视为修改
                updateSubmitForm.chargeList.push(ruleForm.chargeList[i])
                break
              }
            }
            //id被分配完，处理新增
            if (charge_ids.length == 0 && ruleForm.chargeList[i].id == null) {
              ruleForm.chargeList[i].name = ruleForm.chargeList[i].name + '_add'
              updateSubmitForm.chargeList.push(ruleForm.chargeList[i])
            }
          }
        }
        //最终确定需要删除的项
        for (let i = 0; i < charge_ids.length; i++) {
          for (let j = 0; j < verifyRuleForm.chargeList.length; j++) {
            if (verifyRuleForm.chargeList[j].id == charge_ids[i]) {
              verifyRuleForm.chargeList[j].name = verifyRuleForm.chargeList[j].name + '_delete'
              updateSubmitForm.chargeList.push(verifyRuleForm.chargeList[j])
            }
          }
        }
      }
      ruleForm.sellDateType != verifyRuleForm.sellDateType ? updateSubmitForm.sellDateType = ruleForm.sellDateType : null
      ruleForm.sellTimeType != verifyRuleForm.sellTimeType ? updateSubmitForm.sellTimeType = ruleForm.sellTimeType : null
      ruleForm.sellDateScope != verifyRuleForm.sellDateScope ? updateSubmitForm.sellDateScope = ruleForm.sellDateScope : null
      ruleForm.sellTimeScope != verifyRuleForm.sellTimeScope ? updateSubmitForm.sellTimeScope = ruleForm.sellTimeScope : null
      ruleForm.sellWeekDay != verifyRuleForm.sellWeekDay ? updateSubmitForm.sellWeekDay = ruleForm.sellWeekDay : null


      console.log('更新提交表单111：')
      console.log(updateSubmitForm)

      const res: res = await updateProductInfoApi(updateSubmitForm)
      if (res.code === 0) {
        ElMessage({ type: "success", message: "保存成功！" });
        goBack();
      } else {
        ElMessage({ type: "error", message: "保存失败！" });
      }

    }
  }
  )


}

//清空表单（基础）
const resetJichuForm = (formEl: FormInstance | undefined) => {
  //基础
  (ruleForm.sort = ""),
    (ruleForm.name = ""),
    (ruleForm.classify = ""),
    (ruleForm.unit = ""),
    (ruleForm.imgList = []),
    (ruleForm.imgs = []),
    (ruleForm.morenPrice = null),
    (ruleForm.morenpckMoney = 0),
    (ruleForm.morenNumber = 999),
    (ruleForm.delivery = true),
    (ruleForm.oneselfBuy = true),
    (ruleForm.feature = []),
    (ruleForm.participate = true),
    (ruleForm.desc = ""),
    //扩展
    (ruleForm.specificationList = []),
    (ruleForm.propertyList = []),
    (ruleForm.chargeList = []),
    (ruleForm.sellDateType = "全时段售卖"),
    (ruleForm.sellTimeType = "24H全天"),
    (ruleForm.allDateSell = true),
    (ruleForm.allTimeSell = true),
    (ruleForm.sellDateScope = []),
    (ruleForm.sellWeekDay = []),
    (ruleForm.sellTimeScope = []),
    (ruleForm.min_number = 1);
};
//清空表单（扩展）
const resetKuozhanForm = () => { };
//清空表单（其他）
const resetQitaForm = () => { };

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}));
onBeforeMount(() => {
  isupdate.value = props.isupdate;
  pid.value = props.pid;
});

//数据回显并保存
const getEcho = async () => {
  const res = await productInfoApi(pid.value);
  //  console.log(res.data)
  echoProduct.value = res.data;
  // console.log(echoProduct.value);
  //设置回显并保存
  //基础部分
  ruleForm.productId = echoProduct.value.productId
  verifyRuleForm.productId = echoProduct.value.productId

  ruleForm.sort = echoProduct.value.sort;
  verifyRuleForm.sort = echoProduct.value.sort;

  ruleForm.name = echoProduct.value.name;
  verifyRuleForm.name = echoProduct.value.name;

  ruleForm.classify = echoProduct.value.classify;
  verifyRuleForm.classify = echoProduct.value.classify;

  ruleForm.unit = echoProduct.value.unit;
  verifyRuleForm.unit = echoProduct.value.unit;

  ruleForm.desc = echoProduct.value.desc;
  verifyRuleForm.desc = echoProduct.value.desc;

  ruleForm.imgList = JSON.parse(JSON.stringify(echoProduct.value.imgList));//构造file对象
  for (let i = 0; i < echoProduct.value.imgList.length; i++) {

    const content = new Blob([ruleForm.imgList[i]], { type: 'image/jpeg' });
    const filename = 'example.jpeg';
    const file = new File([content], filename, { type: 'image/jpeg' });
    ruleForm.imgList[i].raw = file

  }

  verifyRuleForm.imgList = JSON.parse(JSON.stringify(ruleForm.imgList))

  ruleForm.imgs = JSON.parse(JSON.stringify(echoProduct.value.imgs));
  verifyRuleForm.imgs = JSON.parse(JSON.stringify(echoProduct.value.imgs));

  ruleForm.morenPrice = echoProduct.value.morenPrice;
  verifyRuleForm.morenPrice = echoProduct.value.morenPrice;

  ruleForm.morenpckMoney = echoProduct.value.morenpckMoney;
  verifyRuleForm.morenpckMoney = echoProduct.value.morenpckMoney;

  ruleForm.morenNumber = echoProduct.value.morenNumber;
  verifyRuleForm.morenNumber = echoProduct.value.morenNumber;

  ruleForm.delivery = echoProduct.value.delivery;
  verifyRuleForm.delivery = echoProduct.value.delivery;

  ruleForm.oneselfBuy = echoProduct.value.oneselfBuy;
  verifyRuleForm.oneselfBuy = echoProduct.value.oneselfBuy;

  ruleForm.participate = echoProduct.value.participate;
  verifyRuleForm.participate = echoProduct.value.participate;

  ruleForm.feature = echoProduct.value.feature;
  verifyRuleForm.feature = echoProduct.value.feature;
  //拓展部分
  // ruleForm.specificationList = echoProduct.value.specificationList;
  // verifyRuleForm.specificationList = echoProduct.value.specificationList;
  ruleForm.specificationList = JSON.parse(JSON.stringify(echoProduct.value.specificationList));
  verifyRuleForm.specificationList = JSON.parse(JSON.stringify(echoProduct.value.specificationList));
  // console.log(verifyRuleForm.specificationList)

  ruleForm.propertyList = JSON.parse(JSON.stringify(echoProduct.value.propertyList));
  verifyRuleForm.propertyList = JSON.parse(JSON.stringify(echoProduct.value.propertyList));

  ruleForm.chargeList = JSON.parse(JSON.stringify(echoProduct.value.chargeList));
  verifyRuleForm.chargeList = JSON.parse(JSON.stringify(echoProduct.value.chargeList));

  ruleForm.sellDateType = echoProduct.value.sellDateType;
  verifyRuleForm.sellDateType = echoProduct.value.sellDateType;

  ruleForm.sellTimeType = echoProduct.value.sellTimeType;
  verifyRuleForm.sellTimeType = echoProduct.value.sellTimeType;

  ruleForm.allDateSell = echoProduct.value.allDateSell;
  verifyRuleForm.allDateSell = echoProduct.value.allDateSell;
  ruleForm.allDateSell ? allDate() : customDate();

  ruleForm.allTimeSell = echoProduct.value.allTimeSell;
  verifyRuleForm.allTimeSell = echoProduct.value.allTimeSell;
  ruleForm.allTimeSell ? allTime() : customTime();

  ruleForm.sellWeekDay = echoProduct.value.sellWeekDay;
  verifyRuleForm.sellWeekDay = echoProduct.value.sellWeekDay;

  ruleForm.sellDateScope = echoProduct.value.sellDateScope;
  verifyRuleForm.sellDateScope = echoProduct.value.sellDateScope;

  ruleForm.sellTimeScope = JSON.parse(JSON.stringify(echoProduct.value.sellTimeScope));
  verifyRuleForm.sellTimeScope = JSON.parse(JSON.stringify(echoProduct.value.sellTimeScope))

  ruleForm.min_number = echoProduct.value.min_number;
  verifyRuleForm.min_number = echoProduct.value.min_number;


  // console.log('镜像表单：')
  // console.log(verifyRuleForm)
}
const getClassNames = async () => {
  const res = await classify1ListNameApi()
  classify1ListName.value = res.data
}

const getUnitNames = async () => {
  const res = await unitListNameApi()
  unitListName.value = res.data
}
onMounted(async () => {
  if (isupdate.value == 1) {
    getEcho()
  }
  getClassNames()
  getUnitNames()
});
</script>

<template>
  <div style="position: relative; left: 1%">
    <div>
      <div>
        <el-link :underline="false" @click="goBack">
          <el-icon>
            <CaretLeft />
          </el-icon>
          <strong style="font-size: 18px">商品详情</strong>
        </el-link>
      </div>
    </div>
    <div style="margin-top: 20px">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
        :size="formSize" status-icon>
        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
          <el-tab-pane label="基础" name="first">
            <div>
              <el-form-item label="排序" prop="sort"><el-input-number v-model="ruleForm.sort" :precision="0" :step="1"
                  :min="0" :max="999" /></el-form-item>
              <el-form-item label="商品名称" prop="name"><el-input v-model="ruleForm.name" style="width: 300px"
                  placeholder="请输入商品名称" /></el-form-item>

              <el-form-item label="商品分类" prop="classify">
                <el-select v-model="ruleForm.classify" placeholder="请选择">
                  <el-option v-for="item in classify1ListName" :label=item.class1Name :value=item.class1Name />

                </el-select>
              </el-form-item>

              <el-form-item label="商品单位" prop="unit">
                <el-select v-model="ruleForm.unit" placeholder="请选择">
                  <el-option v-for="item in unitListName" :label=item.name :value=item.name />

                </el-select>
              </el-form-item>

              <el-form-item label="商品简介" prop="desc">
                <el-input v-model="ruleForm.desc" type="textarea" style="width: 300px" />
              </el-form-item>

              <el-form-item label="商品图片" prop="imgList">
                <el-upload v-model:file-list="ruleForm.imgList" action="#" list-type="picture-card"
                  :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :auto-upload="false"
                  @change="checkImageFormat">
                  <el-icon>
                    <Plus />
                  </el-icon>
                </el-upload>

                <label style="
                    position: relative;
                    left: 10px;
                    color: rgb(243, 183, 106);
                  ">提示：第一张图片为首图，商品至少要有一张主图，且至多四张图片</label>

                <el-dialog v-model="dialogVisible">
                  <img w-full :src="dialogImageUrl" alt="Preview Image" />
                </el-dialog>
              </el-form-item>

              <el-form-item label="默认规格" prop="morenPrice">
                <div>
                  <div style="display: flex">
                    <div class="kuozhan-item">
                      <label>价格(元)</label><br />
                      <el-input-number style="width: 140px" v-model="ruleForm.morenPrice" :precision="2" :step="1" @change="" :min="0" />
                    </div>

                    <div class="kuozhan-item">
                      <label>包装费(元)</label><br />
                      <el-input-number style="width: 140px" v-model="ruleForm.morenpckMoney" :precision="2" :step="1"
                        :min="0" />
                    </div>

                    <div class="kuozhan-item">
                      <label>库存(件)</label><br />
                      <el-input-number style="width: 140px" v-model="ruleForm.morenNumber" :precision="0" :step="1" :min="0" />
                    </div>
                  </div>
                </div>
                <label style="
                    position: relative;
                    left: 10px;
                    color: rgb(243, 183, 106);
                  ">提示：默认规格只在该商品没有其他规格时生效</label>
              </el-form-item>

              <el-form-item label="单点配送" prop="delivery">
                <el-switch v-model="ruleForm.delivery" />
                <label style="
                    position: relative;
                    left: 10px;
                    color: rgb(243, 183, 106);
                  ">提示：关闭则用户单点该商品，不会进行配送</label>
              </el-form-item>

              <el-form-item label="单独购买" prop="delivery">
                <el-switch v-model="ruleForm.oneselfBuy" />
                <label style="
                    position: relative;
                    left: 10px;
                    color: rgb(243, 183, 106);
                  ">提示：关闭则用户无法单独买此商品</label>
              </el-form-item>

              <el-form-item label="参与热销排行" prop="participate">
                <el-switch v-model="ruleForm.participate" />
                <label style="
                    position: relative;
                    left: 10px;
                    color: rgb(243, 183, 106);
                  ">提示：关闭则不参与平台商品销量排行榜单</label>
              </el-form-item>

              <el-form-item label="特色标签" prop="feature">
                <el-checkbox-group v-model="ruleForm.feature">
                  <el-checkbox label="招牌" name="type" />
                  <el-checkbox label="热销" name="type" />
                  <el-checkbox label="特色" name="type" />
                  <el-checkbox label="必点" name="type" />
                </el-checkbox-group>
              </el-form-item>
            </div>
          </el-tab-pane>

          <el-tab-pane label="扩展" name="second">
            <div>
              <el-form-item label="售卖规格" v-model="ruleForm.specificationList">
                <div>
                  <div v-for="(spec, index) in ruleForm.specificationList" :key="index" style="display: flex">
                    <div class="kuozhan-item">
                      <label>规格名称</label><br />
                      <el-input style="width: 100px" v-model="spec.name" placeholder="如：分量等" />
                    </div>

                    <div class="kuozhan-item">
                      <label>价格(元)</label><br />
                      <el-input-number style="width: 140px" v-model="spec.price" :precision="2" :step="1" :min="0" />
                    </div>

                    <div class="kuozhan-item">
                      <label>包装费(元)</label><br />
                      <el-input-number style="width: 140px" v-model="spec.pckMoney" :precision="2" :step="1" :min="0" />
                    </div>

                    <div class="kuozhan-item">
                      <label>库存(件)</label><br />
                      <el-input-number style="width: 140px" v-model="spec.number" :precision="0" :step="1" :min="0" />
                    </div>

                    <div style="margin-left: 20px">
                      <br />
                      <el-button @click="delSpec(index)" type="danger" :icon="Delete" circle
                        style="width: 20px; height: 20px" />
                      <!-- <el-button @click="delSpec(index)" :icon="RemoveFilled" style="border: 0px;color: blue;"> </el-button>  -->
                    </div>
                  </div>

                  <el-link :underline="false" @click="addSpecification">
                    <div style="display: block">
                      <el-icon style="color: rgb(55, 135, 247)">
                        <CirclePlusFilled />
                      </el-icon>
                      <label>添加规格,最多20个</label>
                    </div>
                  </el-link>
                </div>
              </el-form-item>

              <el-form-item label="售卖属性" v-model="ruleForm.propertyList">
                <div>
                  <div v-for="(prop, index) in ruleForm.propertyList" :key="index" style="display: flex">
                    <div class="kuozhan-item">
                      <label>属性名称</label><br />
                      <el-input style="width: 100px" v-model="prop.name" placeholder="如：辣度等" />
                    </div>

                    <div class="kuozhan-item">
                      <label>属性值(请至少填写两个,上限10个)</label><br />
                      <div v-for="(value, index) in prop.value" :key="index" style="display: inline">
                        <el-input style="width: 80px" v-model="prop.value[index]" />
                      </div>
                    </div>

                    <div style="margin-left: 20px">
                      <br />
                      <el-button @click="delProp(index)" type="danger" :icon="Delete" circle
                        style="width: 20px; height: 20px" />
                    </div>
                  </div>
                  <el-link :underline="false" @click="addProperty">
                    <div style="display: block">
                      <el-icon style="color: rgb(55, 135, 247)">
                        <CirclePlusFilled />
                      </el-icon>
                      <label>添加属性,最多20个</label>
                    </div>
                  </el-link>
                </div>
              </el-form-item>

              <el-form-item label="售卖加料" v-model="ruleForm.chargeList">
                <div>
                  <div v-for="(charge, index) in ruleForm.chargeList" :key="index" style="display: flex">
                    <div class="kuozhan-item">
                      <label>加料名称</label><br />
                      <el-input style="width: 100px" v-model="charge.name" placeholder="如：加蛋等" />
                    </div>

                    <div class="kuozhan-item">
                      <label>价格</label><br />
                      <el-input-number style="width: 140px" v-model="charge.price" :precision="2" :step="1" :min="0" />
                    </div>

                    <div style="margin-left: 20px">
                      <br />
                      <el-button @click="delCharge(index)" type="danger" :icon="Delete" circle
                        style="width: 20px; height: 20px" />
                    </div>
                  </div>
                  <el-link :underline="false" @click="addCharge">
                    <div style="display: block">
                      <el-icon style="color: rgb(55, 135, 247)">
                        <CirclePlusFilled />
                      </el-icon>
                      <label>添加加料,最多20个</label>
                    </div>
                  </el-link>
                </div>
              </el-form-item>

              <el-form-item label="售卖时间" v-model="ruleForm.sellDateType">
                <el-radio-group v-model="ruleForm.sellDateType">
                  <el-radio @click="allDate" label="全日期售卖" />
                  <el-radio @click="customDate" label="自定义时间" />
                </el-radio-group>

                <div v-if="showDateSelect" style="margin-left: 20px">
                  <div>
                    <div class="block">
                      <span class="demonstration">选择日期段</span>
                      <el-date-picker @change="dateToString"  style="margin-left: 10px; width: 200px"
                        v-model="ruleForm.sellDateScope" type="daterange" range-separator="至"
                        start-placeholder="Start date" end-placeholder="End date" :size="'small'" />

                      
                    </div>

                    <div>
                      <el-checkbox-group v-model="ruleForm.sellWeekDay">
                        <el-checkbox label="周一" name="周一" />
                        <el-checkbox label="周二" name="周二" />
                        <el-checkbox label="周三" name="周三" />
                        <el-checkbox label="周四" name="周四" />
                        <el-checkbox label="周五" name="周五" />
                        <el-checkbox label="周六" name="周六" />
                        <el-checkbox label="周日" name="周日" />
                      </el-checkbox-group>
                    </div>
                    <div>
                      <label>选择时段</label>
                      <div>
                        <el-radio-group v-model="ruleForm.sellTimeType">
                          <el-radio @click="allTime" label="24H全天" />
                          <el-radio @click="customTime" label="自定义时段" />
                        </el-radio-group>
                        <div v-if="showTimeSelect">
                          <el-time-picker v-model="ruleForm.sellTimeScope[0]" placeholder="起始时间"
                            :value-format="pickerFormatText" :format="pickerFormatText" :picker-options="{
                              selectableRange: '08:00:00 - 23:59:00',
                              format: '08:00:00',
                            }" @change="changeTime">
                          </el-time-picker>
                          <span>-</span>
                          <el-time-picker v-model="ruleForm.sellTimeScope[1]" placeholder="结束时间"
                            :value-format="pickerFormatText" :format="pickerFormatText" :picker-options="{
                              selectableRange: `'08:00:00 - 23:59:00`,
                              format: pickerFormatText,
                            }">
                          </el-time-picker>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </el-form-item>
              <el-form-item label="起购数量">
                <el-input-number v-model="ruleForm.min_number" :precision="0" :step="1" :min="0" :max="999" />
              </el-form-item>
            </div>
          </el-tab-pane>
          <el-tab-pane label="其他" name="third">
            <div></div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </div>
    <el-divider />
    <div style="position: relative; left: 42%">
      <!-- 添加商品 -->
        <SButton @click="isupdate == 0 ? submitForm(ruleFormRef) : submitUpdateForm(ruleFormRef)" title="保存" ></SButton>
      <!-- 编辑商品 -->
      <SButton v-if="isupdate == 0" @click="resetJichuForm(ruleFormRef)" title="清空" type="reset"></SButton>
    </div>
  </div>
</template>

<style scoped lang="scss">
.kuozhan-item {
  margin-left: 20px;
}

::v-deep .el-tabs__item.is-active {
  color: $seleceted;
  opacity: 1;
}
::v-deep .el-tabs__item:hover {
  color: $seleceted;
  cursor: pointer;
  opacity: 1;
}

::v-deep .el-tabs__active-bar {
  background-color:$seleceted;
}
.el-switch__core {
  background-color: #ff6600; /* 指定选中时的背景颜色 */
  border-color: #ff6600; /* 指定选中时的边框颜色 */
}
// 控制switch
// ::v-deep .el-switch.is-checked .el-switch__core .el-switch__action {
//   left: 1px !important;
// }
 
// ::v-deep .el-switch__core .el-switch__action {
//   left: calc(100% - 17px) !important;
// }




</style>
